package com.shawn.integeration.async.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author shawn
 * @description: 自定义线程池配置
 * @date 2024/1/15
 */
@Configuration
public class ThreadPoolConfig {
    private int corePoolSize = 50;
    private int maxPoolSize = 200;
    private int queueCapacity = 1000;
    private int keepAliveSeconds = 300;
    private int awaitTerminationSeconds = 60;

    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 线程池的最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 线程池的核心线程数
        executor.setCorePoolSize(corePoolSize);
        // 线程池的队列容量
        executor.setQueueCapacity(queueCapacity);
        // 线程池中空闲线程的存活时间
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // 线程池对拒绝任务(无线程可用)的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 线程池在关闭时是否等待所有任务完成。
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 线程池在关闭时最多等待的时间
        executor.setAwaitTerminationSeconds(awaitTerminationSeconds);
        // 线程池中线程的名称前缀
        executor.setThreadNamePrefix("AsyncThread-");
        return executor;
    }
}
